package com.jiuyin.dianjing.ui.activity.setting;

import android.graphics.Color;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.decoration.CustomDividerItemDecoration;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.UserItemModel;
import com.jiuyin.dianjing.ui.activity.base.BaseSwipeRefreshActivity;
import com.jiuyin.dianjing.ui.fragment.community.PostFragment;
import com.jiuyin.dianjing.ui.fragment.main.FragmentFive;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_MODEL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_USER_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CIRCLE_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CLIENTUSER_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_HEADER;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NICK_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TARGETID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TEAM_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_UNIVERSITYCLUB_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_UNIVERSITY_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_ATTENTION_CLUB;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_ATTENTION_TEAM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_ATTENTION_USER;

/**
 * 关注
 */
public class SettingAttentionActivity extends BaseSwipeRefreshActivity<UserItemModel> {
    private boolean mChanged;

    public SettingAttentionActivity() {
        super(PAGE_NUM);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_setting_my_attention;
    }

    @Override
    protected void initData() {
        mAdapter = new BaseRecyclerAdapter<UserItemModel>(R.layout.item_user) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, UserItemModel model, int position) {
                if (null != model) {
                    holder.text(R.id.tv_name, model.getNickname());
                    ImageView ivGame = holder.itemView.findViewById(R.id.img_header);
                    Glide.with(SettingAttentionActivity.this)
                            .load(model.getHeader())
                            .override(DisplayUtil.dp2px(SettingAttentionActivity.this, 27), DisplayUtil.dp2px(SettingAttentionActivity.this, 27))
                            .into(ivGame);
                }
            }
        };
        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator = (leftMenu, rightMenu, position) -> {
            int height = ViewGroup.LayoutParams.WRAP_CONTENT;
            int width = getResources().getDimensionPixelSize(R.dimen.dp_40);
            SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
            deleteItem.setText(R.string.setting_attention_delete);
            deleteItem.setBackground(R.drawable.btn_red_bg);
            deleteItem.setTextColor(Color.WHITE);
            deleteItem.setWidth(width);
            deleteItem.setHeight(height);
            rightMenu.addMenuItem(deleteItem);
        };
        OnItemMenuClickListener menuClickListener = (menuBridge, position) -> {
            menuBridge.closeMenu();
            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                delete(mAdapter.getItem(position));
            }
        };
        mRcvPage.addItemDecoration(new CustomDividerItemDecoration(this));//添加分割线
        mRcvPage.setSwipeMenuCreator(mSwipeMenuCreator);
        mRcvPage.setOnItemMenuClickListener(menuClickListener);
        mRcvPage.setAdapter(mAdapter);
        fetchData();
    }

    @Override
    protected void initView() {
        setTitle(R.string.my_attention);
    }

    @Override
    protected void fetchData() {
        HashMap<String, Object> data = new HashMap<>();
        data.put(KEY_TOKEN, HelperApplication.getToken());
        data.put(KEY_PAGE_NUM, mPageNum);
        JSONObject jsonObject = new JSONObject(data);
        ProgressDialogCallback progress = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                if (null != data && data.has(KEY_ATTENTION_USER_LIST)) {
                    JsonArray jsonArray = data.getAsJsonArray(KEY_ATTENTION_USER_LIST);
                    int size = jsonArray.size();
                    if (0 != size) {
                        List<UserItemModel> list = new ArrayList<>(size);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JsonObject object = jsonArray.get(i).getAsJsonObject();
                            String model = object.get(KEY_ATTENTION_MODEL).getAsString();
                            if (VALUE_ATTENTION_USER.equals(model)) {
                                String nickname = object.get(KEY_NICK_NAME).getAsString();
                                String header = object.get(KEY_HEADER).getAsString();
                                String clientuser_id = object.get(KEY_CLIENTUSER_ID).getAsString();
                                UserItemModel itemModel = new UserItemModel();
                                itemModel.setNickname(nickname);
                                itemModel.setHeader(header);
                                itemModel.setId(clientuser_id);
                                list.add(itemModel);
                            } else if (VALUE_ATTENTION_TEAM.equals(model)) {
                                String name = object.get(KEY_NAME).getAsString();
                                String logo = object.get(KEY_LOGO).getAsString();
                                String team_id = object.get(KEY_TEAM_ID).getAsString();
                                UserItemModel itemModel = new UserItemModel();
                                itemModel.setNickname(name);
                                itemModel.setHeader(logo);
                                itemModel.setId(team_id);
                                list.add(itemModel);
                            } else if (VALUE_ATTENTION_CLUB.equals(model)) {
                                String university_name = object.get(KEY_UNIVERSITY_NAME).getAsString();
                                String circle_logo = object.get(KEY_CIRCLE_LOGO).getAsString();
                                String universityclub_id = object.get(KEY_UNIVERSITYCLUB_ID).getAsString();
                                UserItemModel itemModel = new UserItemModel();
                                itemModel.setNickname(university_name);
                                itemModel.setHeader(circle_logo);
                                itemModel.setId(universityclub_id);
                                list.add(itemModel);
                            }
                        }
                        dealWithSuccessInfo(list);
                    } else {
                        dealOtherInfo();
                    }
                } else {
                    dealOtherInfo();
                }
            }

            @Override
            public void onFail(String msg) {
                LogUtil.log("SettingAttentionActivity onFail msg = " + msg);
                dealOtherInfo();
            }

            @Override
            public void onError(String msg) {
                LogUtil.log("SettingAttentionActivity onError msg = " + msg);
                dealOtherInfo();
            }
        };
        ServerApi.post(ApiEnum.APP_GET_USER_ATTENTION_LIST_API.getUrl(), jsonObject, null,
                progress, d -> addDisposable(d), request);

    }

    /**
     * 取消关注
     */
    private void delete(final UserItemModel userItemModel) {
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_TARGETID, userItemModel.getId());
        params.put(KEY_TYPE, 0);
        params.put(KEY_ATTENTION_MODEL, VALUE_ATTENTION_USER);
        JSONObject json = new JSONObject(params);
        ApiResultCallback apiResultCallback = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                mChanged = true;
                int size = mAdapter.remove(userItemModel).getCount();
                EventBus.getDefault().post(new RefreshEvent(FragmentFive.class.getSimpleName()));
                EventBus.getDefault().post(new RefreshEvent(PostFragment.class.getSimpleName()));
                if (0 == size) {
                    showEmpty();
                }
            }

            @Override
            public void onFail(String msg) {
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log(msg);
            }
        };
        ServerApi.post(ApiEnum.APP_ADD_ATTENTION_LOG.getUrl(), json, null,
                progress, d -> addDisposable(d), apiResultCallback);
    }

    @Override
    public void onBackPressed() {
        if (mChanged) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }
}
